package com.wfs.myapp.controller.bk;

import com.wfs.myapp.common.ApiResult;
import com.wfs.myapp.common.Constant;
import com.wfs.myapp.entity.domain.bk.BkOrder;
import com.wfs.myapp.entity.dto.req.bk.AddBookReqDto;
import com.wfs.myapp.entity.dto.req.bk.ApproveReqDto;
import com.wfs.myapp.entity.dto.req.bk.BorrowReqDto;
import com.wfs.myapp.service.BkBookService;
import com.wfs.myapp.service.BkOrderService;
import com.wfs.myapp.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/bk/order")
@Api(value = "订单", tags = "订单")
@Slf4j
public class OrderController {

    @Autowired
    private BkOrderService bkOrderService;

    @PostMapping("/borrow")
    @ApiOperation(value = "申请借书")
    public ApiResult<?> borrow(@Valid @RequestBody BorrowReqDto borrowReqDto, HttpServletRequest request) {
        Long userId = JwtUtil.getUserId(request.getHeader(Constant.AUTHORIZATION));
        return bkOrderService.borrow(userId, borrowReqDto);
    }

    @PostMapping("/borrowProcess")
    @ApiOperation(value = "订单状态修改")
    public ApiResult<?> borrowProcess(@Valid @RequestBody ApproveReqDto approveReqDto, HttpServletRequest request) {
        Long userId = JwtUtil.getUserId(request.getHeader(Constant.AUTHORIZATION));
        return bkOrderService.borrowProcess(userId, approveReqDto);
    }

    /**
     *
     * @param page
     * @param size
     * @param status  0申请 1已借 2拒绝 3逾期 4已还
     * @param request
     * @return
     */
    @GetMapping("/myOrderList")
    @ApiOperation(value = "我的订单列表")
    public ApiResult<?> myOrderList(@RequestParam("page") Integer page,
                                    @RequestParam("size") Integer size,
                                    @RequestParam(value = "direction") Integer direction,
                                    @RequestParam(value = "status", required = false) String status,
                                    HttpServletRequest request) {
        Long userId = JwtUtil.getUserId(request.getHeader(Constant.AUTHORIZATION));
        List<Integer> statusList = null;
        if (StringUtils.isNotBlank(status)) {
            List<String> strings = Arrays.asList(status.split(","));
            statusList = strings.stream().filter(item -> StringUtils.isNotBlank(item)).map(Integer::valueOf).collect(Collectors.toList());
        }
        log.info("statusList: {}", statusList);
        return bkOrderService.myOrderList(userId, direction, statusList, page, size);
    }


}
